package com.serie402.business.dao;

import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;

import com.kiss.fw.dao.AbstractDAO;
import com.kiss.fw.dao.DAOMapper;
import com.kiss.fw.exceptions.MapperException;
import com.kiss.fw.exceptions.StoredProcedureException;
import com.kiss.fw.utils.Constants;
import com.kiss.fw.utils.Util;
import com.serie402.business.dao.mappers.AuthorMapper;
import com.serie402.business.dao.mappers.EventMapper;
import com.serie402.business.dao.mappers.GalleryMapper;
import com.serie402.business.dao.mappers.NewsMapper;

public abstract class Serie402DAO extends AbstractDAO {
	protected static final class MapperFactory {
		private static final Logger mapperFactoryLogger = Logger.getLogger(MapperFactory.class);
		
		private MapperFactory() {
		}
		
		private static DAOMapper getMapper(SqlSession _sqlSession, Class<? extends DAOMapper> _mapperClass) throws MapperException {
			DAOMapper returnVal = null;
			
			try {
				// get the mapper that will be used
				returnVal = _sqlSession.getMapper(_mapperClass);
			}
			catch(Exception _exception) {
				// close the sqlSession if we were unable to get the Mapper
				closeSqlSession(_sqlSession);
				
				// log error
				Util.handleException(mapperFactoryLogger, "Error getting mapper", _exception);
				
				// throw singleton exception
				throw Constants.Exceptions.MAPPER_EXCEPTION;
			}
			
			return returnVal;
		}
		
		public static AuthorMapper getAuthorMapper(SqlSession _sqlSession) throws MapperException {
			return (AuthorMapper)getMapper(_sqlSession, AuthorMapper.class);
		}
		
		public static EventMapper getEventMapper(SqlSession _sqlSession) throws MapperException {
			return (EventMapper)getMapper(_sqlSession, EventMapper.class);
		}
		
		public static GalleryMapper getGalleryMapper(SqlSession _sqlSession) throws MapperException {
			return (GalleryMapper)getMapper(_sqlSession, GalleryMapper.class);
		}
		
		public static NewsMapper getNewsMapper(SqlSession _sqlSession) throws MapperException {
			return (NewsMapper)getMapper(_sqlSession, NewsMapper.class);
		}
	}
	
	protected static void handleException(final Logger _logger, final String _message, final Throwable _throwable) throws StoredProcedureException {
		Util.handleException(_logger, _message, _throwable);
		throw Constants.Exceptions.STORED_PROCEDURE_EXCEPTION;
	}
}